package com.hzh.page.common.exception;


import com.hzh.page.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.hzh.page.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R HandleValidException(MethodArgumentNotValidException e) {
        Map<String, String> errorMap = new HashMap<>();
        log.error("数据检验异常：{},异常类型为：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(ResponseEnum.VALID_EXCEPTION.getCode(), ResponseEnum.VALID_EXCEPTION.getMessage()).put("errorMap", errorMap);
    }
}
